package top.suven.base.http.admin.frame.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@Lazy
@MapperScan(basePackages="cn.com.gc.hsz.admin.**.dao",sqlSessionFactoryRef = "sqlSessionFactory")
public class MyBatisAutoConfiguration implements ApplicationContextAware{
//    @Autowired
//    private DataSource dataSource;
    //是否开启mybatis
    private static String MYBATIS_IS_OPEN = "gc.mybatis.isOpen";//
    private static String MYBATIS_BASE_PACKAGE = "gc.mybatis.basePackage";//
    private boolean isOpen;
    private String basePackage;
    private BeanDefinitionRegistry registry;

    private ApplicationContext applicationContext;
//    /**
//     * master DataSource
//     * @Primary 注解用于标识默认使用的 DataSource Bean，因为有5个 DataSource Bean，该注解可用于 master
//     * 或 slave DataSource Bean, 但不能用于 dynamicDataSource Bean, 否则会产生循环调用
//     *
//     * @ConfigurationProperties 注解用于从 application.properties 文件中读取配置，为 Bean 设置属性
//     * @return data source
//     */
//    @Bean("userDataSource")
//    @Primary
//    @ConfigurationProperties(prefix = "gc.datasource.druid.user")
//    public DataSource userDataSource() {
//        return DruidDataSourceBuilder.create().build();
//    }
//
//    /**
//     * Slave alpha data source.
//     *
//     * @return the data source
//     */
//    @Bean("secDataSource")
//    @ConfigurationProperties(prefix = "gc.datasource.druid.sec")
//    public DataSource configDataSource() {
//        return DruidDataSourceBuilder.create().build();
//    }
//
//
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
//    public MyBatisAutoConfiguration(BeanDefinitionRegistry registry,RelaxedPropertyResolver property){
//        isOpen = property.getProperty(MYBATIS_IS_OPEN,Boolean.class,false);
//        basePackage = property.getProperty(MYBATIS_BASE_PACKAGE);
//        this.registry = registry;
//    }
//
//    public void registerSqlSessionFactory(DataSource dataSource)  {
//        BeanDefinitionBuilder sqlSessionFactory = BeanDefinitionBuilder.genericBeanDefinition(SqlSessionFactoryBean.class);
//        sqlSessionFactory.addPropertyValue(MyBatisConfiguration.DATA_SOURCE, dataSource);
//        registry.registerBeanDefinition("sqlSessionFactory", sqlSessionFactory.getBeanDefinition());
//    }
//
//    public void registerTxManager(DataSource dataSource) {
//        BeanDefinitionBuilder sqlSessionFactory = BeanDefinitionBuilder.genericBeanDefinition(DataSourceTransactionManager.class);
//        sqlSessionFactory.addPropertyValue(MyBatisConfiguration.DATA_SOURCE, dataSource);
//        registry.registerBeanDefinition("txManager", sqlSessionFactory.getBeanDefinition());
//    }

//    @Bean("dataSource")
//    public DataSource routingDataSource() {
//        DynamicDataSource dataSource = new DynamicDataSource();
//        Set<DataSourceGroupNameEnum> sourceNames = new HashSet<>();
//        sourceNames.addAll(DataSourceGroupNameEnum.getValues());
//        if (sourceNames == null || sourceNames.isEmpty()) {
//            throw  new RuntimeException("DynamicDataSource init DataSource isEmpty ");
//        }
//        for (DataSourceGroupNameEnum dataName : sourceNames) {
//            dataSource.initDataByGroup(dataName,applicationContext);
//        }
//        dataSource.setTargetDataSources();
//
//
//        return dataSource;
//    }

    /**
     * Dynamic data source.
     *
     * @return the data source
     */
//    @Bean("dynamicDataSource")
//    public DataSource dynamicDataSource() {
//        DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();
//        Map<Object, Object> dataSourceMap = new HashMap<>(2);
//        dataSourceMap.put(DataSourceGroupNameEnum.DATA_NAME_USER.getValue(), userDataSource());
//        dataSourceMap.put(DataSourceGroupNameEnum.DATA_NAME_CONFIG.getValue(), configDataSource());
//
//        // 将 master 数据源作为默认指定的数据源
//        dynamicRoutingDataSource.setDefaultTargetDataSource(userDataSource());
//        // 将 master 和 slave 数据源作为指定的数据源
//        dynamicRoutingDataSource.setTargetDataSources(dataSourceMap);
//
//        // 将数据源的 key 放到数据源上下文的 key 集合中，用于切换时判断数据源是否有效
//        DynamicDataSourceContextHolder.dataSourceKeys.addAll(dataSourceMap.keySet());
//        return dynamicRoutingDataSource;
//    }
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
        DataSource dataSource = applicationContext.getBean("dataSource",DataSource.class);
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        return sqlSessionFactory;
    }

    @Bean
    public PlatformTransactionManager txManager() throws Exception {
        DataSource dataSource = applicationContext.getBean("dataSource",DataSource.class);
        return new DataSourceTransactionManager(dataSource);
    }

//    public void mapperScannerConfigurer(ApplicationContext applicationContext) {
//        DataSource dataSource = applicationContext.getBean("dataSource",DataSource.class);
//        this.registerSqlSessionFactory(dataSource);
//        this.registerTxManager(dataSource);
//        BeanDefinitionBuilder configurer = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);
//        configurer.addPropertyValue(MyBatisConfiguration.BASE_PACKAGE, basePackage);
//        configurer.addPropertyValue(MyBatisConfiguration.SQL_SESSION_FACTORY_BEAN_NAME, "sqlSessionFactory");
//        registry.registerBeanDefinition("mapperScannerConfigurer", configurer.getBeanDefinition());
//    }


//    @Bean
//    public static MapperScannerConfigurer mapperScannerConfigurer() {
//        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
////        String basePackage = getMyBatisBasePackage(
////                environment,
////                "gc.mybatis.basePackage",
////                null);
//        configurer.setBasePackage("cn.com.gc.hsz.admin.**.dao");
//        configurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
//        return configurer;
//    }
//
//    private static String getMyBatisBasePackage(ConfigurableEnvironment environment, String key, String listKey) {
//        StringBuilder basePackageBuffer = new StringBuilder();
//        String basePackage = environment.getProperty(key);
//        if (basePackage != null) {
//            basePackageBuffer.append(basePackage);
//        }
//        if(StringUtils.isNotBlank(listKey)) {
//            List<String> basePackages = environment.getProperty(listKey, List.class);
//            if (basePackages != null && basePackages.size() > 0) {
//                if (basePackageBuffer.length() > 0) {
//                    basePackageBuffer.append(',');
//                }
//                basePackageBuffer.append(basePackages.get(0));
//                for (int i = 1; i < basePackages.size(); ++i) {
//                    basePackageBuffer.append(',');
//                    basePackageBuffer.append(basePackages.get(i));
//                }
//            }
//        }
//        return basePackageBuffer.toString();
//    }

}
